package com.play.ballen.home.vm

import androidx.lifecycle.MutableLiveData
import com.play.ballen.home.entity.ArticleInfo
import com.play.ballen.network.ApiRepository
import com.play.ballen.network.BallenRxHelper
import com.yuven.appframework.busevent.SingleLiveEvent
import com.yuven.appframework.network.RxSchedulerHelper
import com.yuven.appframework.util.addToDisposable
import com.yuven.baselib.component.viewmodel.BaseViewModel
import com.yuven.baselib.utils.Logger

class ArticleVM : BaseViewModel() {

    private val model = ApiRepository()

    var page = 1
    private val pageSize = 20

    val articleInfo = MutableLiveData<ArticleInfo>()

    val listArticle = MutableLiveData<List<ArticleInfo>?>()
    val actionGetArticleListFailure = SingleLiveEvent<String>()

    fun getArticleList() {
        val map = mutableMapOf<String, Any>()
        map["page"] = page
        map["pagesize"] = pageSize

        model.getArticleList(map)
            .onErrorResumeNext(BallenRxHelper.HttpErrorHandleFunc())
            .compose(BallenRxHelper.transformResponse())
            .compose(RxSchedulerHelper.io_main())
            .subscribe({ data ->
                listArticle.value = data
                Logger.i("ArticleVM.getArticleList success list size = $data")
            }, { throwable ->
                actionGetArticleListFailure.value = throwable.message
                Logger.i("ArticleVM.getArticleList error,msg = ${throwable.message}")
            }).addToDisposable(compositeDisposable)
    }

    fun getArticleDetail(id: String) {
        model.getArticleDetail(id)
            .onErrorResumeNext(BallenRxHelper.HttpErrorHandleFunc())
            .compose(BallenRxHelper.transformResponse())
            .compose(RxSchedulerHelper.io_main())
            .subscribe({
                Logger.i("ArticleVM.getArticleDetail success")
                articleInfo.value = it
            }, { throwable ->
                toastLiveData.value = throwable.message
                Logger.i("ArticleVM.getArticleDetail error,msg = ${throwable.message}")
            }).addToDisposable(compositeDisposable)
    }

}